/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode[]} lists
 * @return {ListNode}
 */
var mergeKLists = function (lists) {
  let res = new ListNode(-1)
  let p1 = res
  for (let i = 0; i < lists.length; i++) {
    let p2 = lists[i]
    while (p2) {
      p1.next = p2
      p2 = p2.next
      p1 = p1.next
    }
  } // 合并成一个链表
  // console.log(res)
  // 对这个链表进行排序
  for (let p3 = res.next; p3; p3 = p3.next) {
    let minVal = p3.val
    let minNode = p3 // 最小的节点位置
    for (let p4 = p3.next; p4; p4 = p4.next) {
      if (p4.val < minVal) { // 找到最小的节点
        minVal = p4.val
        minNode = p4
      }
    }
    // 交换最小的节点
    let temp = p3.val
    p3.val = minVal
    minNode.val = temp
  }
  return res.next
};